<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#div1 {
				width: 300px;
				height: 50px;
				margin: 0px auto;
				background-color: skyblue;
				text-align: center;
				position: absolute;
				top: 50px;
				left: 50%;
				line-height: 10px;
			}

			body {
				height: 3000px;
			}

			#test {
				position: fixed;
				right: 100px;
				bottom: 100px;
			}
		</style>
	</head>
	<body>
		<div id="div1">
			<h1>我是页面顶部!</h1>
		</div>
		<button id="test">回到顶部</button>
	</body>
	<script type="text/javascript">
		window.onscroll = function() {
			console.log("滚了");
			// 获取卷去的高度 ；1.存在兼容 有没有文档声明 ，如果有声明 document.documentElement.scrollTop
			// 没有文档声明 document.body.scrollTop 
			// 2. 可以获取 且可以设置 卷去的高度；
			var top = document.documentElement.scrollTop || document.body.scrollTop;
			if (top > 100) {
				div1.style.position = "fixed";
				div1.style.top = 0;
			} else {
				div1.style.position = "absolute";
				div1.style.top = "100px";
			}
		}
		test.onclick = function() {
			// document.body.scrollTop = document.documentElement.scrollTop = 0;
			settop();
		}

		function settop() {
			setTimeout(function() {
				top -= 100;
				document.documentElement.scrollTop = top;
				if (top > 0) {
					settop();
				}
			}, 1000);
		}
	</script>
</html>
